Option Strict Off
Option Explicit On

Imports System.IO
Imports Microsoft.Win32
Imports System.Runtime.InteropServices
Imports System
Imports System.Threading
Public Module mod_BikiUSB
    Friend Declare Function FT_CreateDeviceInfoList Lib "ftd2xx.dll" (ByRef ulngNumDevs As UInt32) As FT_return
    Friend Declare Function FT_GetDeviceInfoDetail Lib "ftd2xx.dll" Alias "FT_GetDeviceInfoDetail" (ByVal dwIndex As Int32, ByRef lpdwFlags As UInt32, ByRef lpdwType As UInt32, ByRef lpdwID As UInt32, ByRef lpdwLocid As UInt32, ByVal pucSerialNumber As Byte(), ByVal pucDescription As Byte(), ByRef lngHandle As Integer) As FT_return
    Friend Declare Function FT_GetNumberOfDevices Lib "ftd2xx.dll" Alias "FT_ListDevices" (ByRef lngNumberOfDevices As Integer, ByVal pvArg2 As String, ByVal lngFlags As Integer) As FT_return
    Friend Declare Function FT_GetDeviceString Lib "ftd2xx.dll" Alias "FT_ListDevices" (ByVal lngDeviceIndex As Integer, ByVal lpszDeviceString As String, ByVal lngFlags As Integer) As FT_return
    Friend Declare Function FT_GetDeviceInfo Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lngFT_Type As Integer, ByRef lngID As Integer, ByVal pucSerialNumber As String, ByVal pucDescription As String, ByRef pvDummy As Byte) As FT_return

    '===========================================================================================================================
    ' Declarations for functions in FTD2XX.dll:
    '===========================================================================================================================
    Friend Declare Function FT_OpenByIndex Lib "ftd2xx.dll" Alias "FT_Open" (ByVal intDeviceNumber As Integer, ByRef lngHandle As Integer) As FT_return
    Friend Declare Function FT_OpenEx Lib "ftd2xx.dll" Alias "FT_OpenEx" (ByVal pchArg As String, ByVal Flags As FT_Open, ByRef lngHandle As Integer) As FT_return
    Friend Declare Function FT_OpenBySerialNumber Lib "ftd2xx.dll" Alias "FT_OpenEx" (ByVal SerialNumber As String, ByVal lngFlags As Integer, ByRef lngHandle As Integer) As FT_return
    Friend Declare Function FT_OpenByDescription Lib "ftd2xx.dll" Alias "FT_OpenEx" (ByVal Description As String, ByVal lngFlags As Integer, ByRef lngHandle As Integer) As FT_return
    Friend Declare Function FT_Close Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_Read_String Lib "ftd2xx.dll" Alias "FT_Read" (ByVal lngHandle As Integer, ByVal lpvBuffer As String, ByVal lngBufferSize As Integer, ByRef lngBytesReturned As Integer) As FT_return
    Friend Declare Function FT_Write_String Lib "ftd2xx.dll" Alias "FT_Write" (ByVal lngHandle As Integer, ByVal lpvBuffer As String, ByVal lngBufferSize As Integer, ByRef lngBytesWritten As Integer) As FT_return
    Friend Declare Function FT_Read_Bytes Lib "ftd2xx.dll" Alias "FT_Read" (ByVal lngHandle As Integer, ByRef lpvBuffer As Byte, ByVal lngBufferSize As Integer, ByRef lngBytesReturned As Integer) As FT_return
    Friend Declare Function FT_Write_Bytes Lib "ftd2xx.dll" Alias "FT_Write" (ByVal lngHandle As Integer, ByRef lpvBuffer As Byte, ByVal lngBufferSize As Integer, ByRef lngBytesWritten As Integer) As FT_return
    Friend Declare Function FT_SetBaudRate Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal lngBaudRate As Integer) As FT_return
    Friend Declare Function FT_SetDivisor Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal intDivisor As Integer) As FT_return
    Friend Declare Function FT_SetDataCharacteristics Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal byWordLength As FT_Bits, ByVal byStopBits As FT_Stop_Bits, ByVal byParity As FT_Parity) As FT_return
    Friend Declare Function FT_SetFlowControl Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal intFlowControl As FT_Flow, ByVal byXonChar As Byte, ByVal byXoffChar As Byte) As FT_return
    Friend Declare Function FT_ResetDevice Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_SetDtr Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_ClrDtr Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_SetRts Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_ClrRts Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_GetModemStatus Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lngModemStatus As Integer) As FT_return
    Friend Declare Function FT_SetChars Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal byEventChar As Byte, ByVal byEventCharEnabled As Byte, ByVal byErrorChar As Byte, ByVal byErrorCharEnabled As Byte) As FT_return
    Friend Declare Function FT_Purge Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal lngMask As FT_Purg) As FT_return
    Friend Declare Function FT_SetTimeouts Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal lngReadTimeout As Integer, ByVal lngWriteTimeout As Integer) As FT_return
    Friend Declare Function FT_GetQueueStatus Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lngRxBytes As Integer) As FT_return
    Friend Declare Function FT_GetLatencyTimer Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef ucTimer As Byte) As FT_return
    Friend Declare Function FT_SetLatencyTimer Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal ucTimer As Byte) As FT_return
    Friend Declare Function FT_GetBitMode Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef ucMode As Byte) As FT_return
    Friend Declare Function FT_SetBitMode Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal ucMask As Byte, ByVal ucEnable As Byte) As FT_return
    Friend Declare Function FT_SetUSBParameters Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal lngInTransferSize As Integer, ByVal lngOutTransferSize As Integer) As FT_return
    Friend Declare Function FT_SetBreakOn Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_SetBreakOff Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_GetStatus Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lngamountInRxQueue As Integer, ByRef lngAmountInTxQueue As Integer, ByRef lngEventStatus As Integer) As FT_return

    Friend Declare Function FT_SetEventNotification Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal lngEventMask As FT_Events, ByVal lngEvent As Integer) As FT_return
    Friend Declare Function FT_CyclePort Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_ResetPort Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_GetDriverVersion Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef dwDriverVersion As UInt32) As FT_return
    Friend Declare Function FT_GetLibraryVersion Lib "ftd2xx.dll" (ByRef dwDLLVersion As UInt32) As FT_return
    Friend Declare Function FT_Reload Lib "ftd2xx.dll" (ByVal wVID As UShort, ByVal wPID As UShort) As FT_return
    Friend Declare Function FT_StopInTask Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    Friend Declare Function FT_RestartInTask Lib "ftd2xx.dll" (ByVal lngHandle As Integer) As FT_return
    '==============================================================
    'Declarations for the EEPROM-accessing functions in FTD2XX.dll:
    '==============================================================
    'UPGRADE_WARNING: Structure FT_PROGRAM_DATA may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"'
    Friend Declare Function FT_EE_Program Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lpData As FT_PROGRAM_DATA) As FT_return
    Friend Declare Function FT_EE_Read Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lpData As FT_PROGRAM_DATA) As FT_return
    Friend Declare Function FT_EE_UASize Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByRef lpdwSize As Integer) As FT_return
    Friend Declare Function FT_EE_UAWrite Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal pucData() As Byte, ByVal dwDataLen As Integer) As FT_return
    Friend Declare Function FT_EE_UARead Lib "ftd2xx.dll" (ByVal lngHandle As Integer, ByVal pucData() As Byte, ByVal dwDataLen As Integer, ByRef lpdwBytesRead As Integer) As FT_return

    ''' <summary>
    ''' Structure of Device info for use with FT_GetDeviceInfoDetail
    ''' </summary>
    ''' <remarks></remarks>
    Friend Structure FT_DEVICE_INFO
        Dim nIndex As UInt32
        Dim nFlags As UInt32
        Dim nType As FT_DEVICE
        Dim nID As UInt32
        Dim nLocid As UInt32
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=16)> Dim SerialNumber As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=64)> Dim Description As String
        Dim nHandle As Integer

        Dim pchSerial As Byte() ' fuck .net is gay
        Dim pchDesc As Byte()
    End Structure
    '====================================================================
    'Type definition as equivalent for C-structure "ft_program_data" used
    'in FT_EE_READ and FT_EE_WRITE;
    'ATTENTION! The variables "Manufacturer", "ManufacturerID",
    '"Description" and "SerialNumber" are passed as POINTERS to
    'locations of Bytearrays. Each Byte in these arrays will be
    'filled with one character of the whole string.
    '(See below, calls to "agGetAddressForObject")
    '=====================================================================
    Friend Structure FT_PROGRAM_DATA
        Dim VendorId As Short '0x0403
        Dim ProductId As Short '0x6001
        Dim Manufacturer As Integer '32 "FTDI"
        Dim ManufacturerId As Integer '16 "FT"
        Dim description As Integer '64 "USB HS Serial Converter"
        Dim SerialNumber As Integer '16 "FT000001" if fixed, or NULL
        Dim MaxPower As Short ' // 0 < MaxPower <= 500
        Dim PnP As Short ' // 0 = disabled, 1 = enabled
        Dim SelfPowered As Short ' // 0 = bus powered, 1 = self powered
        Dim RemoteWakeup As Short ' // 0 = not capable, 1 = capable
        ' Rev4 extensions:
        Dim Rev4 As Boolean ' // true if Rev4 chip, false otherwise
        Dim IsoIn As Boolean ' // true if in endpoint is isochronous
        Dim IsoOut As Boolean ' // true if out endpoint is isochronous
        Dim PullDownEnable As Boolean ' // true if pull down enabled
        Dim SerNumEnable As Boolean ' // true if serial number to be used
        Dim USBVersionEnable As Boolean ' // true if chip uses USBVersion
        Dim USBVersion As Short ' // BCD (0x0200 => USB2)
    End Structure

    Friend Enum BikiAction As UInt32
        BK_NONE = 0
        BK_MAP1 = &H1
        BK_MAP2 = &H2
        BK_MAP3 = &H4
        BK_MAP4 = &H8
        BK_MAP5 = &H10
        BK_MAP6 = &H20
        BK_MAP7 = &H40
        BK_MAP8 = &H80
        BK_MAP9 = &H100
        BK_MAP10 = &H200
        BK_MAP11 = &H400
        BK_MAP12 = &H800
        BK_MAP13 = &H1000
        BK_MAP14 = &H2000
        BK_MAP15 = &H4000
        BK_CFG = &H8000
        BK_EEPROM = &H10000
        BK_ALL = &H20000
        BK_CURRENT = &H40000
        BK_MAPS = &H7FFF
        BK_EVERYTHING = BK_MAPS Or BK_CFG Or BK_EEPROM
    End Enum
    Friend Enum FT_DEVICE As UInteger
        FT_DEVICE_232BM = 0
        FT_DEVICE_232AM = 1
        FT_DEVICE_100AX = 2
        FT_DEVICE_UNKNOWN = 3
        FT_DEVICE_2232C = 4
        FT_DEVICE_232R = 5
    End Enum
    ''' <summary>
    ''' This enumator defines Integer values in byte offset from zero of the USB FT 232's EEPROM space
    ''' </summary>
    ''' <remarks></remarks>
    Friend Enum Biki_USBvars As Short
        UV_Baud = 0
        UV_EcuFLASH_CRC = 2
        UV_BikEEPROM_CRC = 6
        UV_EcuFLASH_CRC_MAP_2 = &HA
        UV_EcuFLASH_CRC_MAP_3 = &HE
        UV_FirmWare = &H12
        UV_BikPROG = &H14
        UV_BikSync = &H18
    End Enum

    Public Enum FT_return As Short
        FT_OK = 0
        FT_INVALID_HANDLE = 1
        FT_DEVICE_NOT_FOUND = 2
        FT_DEVICE_NOT_OPENED = 3
        FT_IO_ERROR = 4
        FT_INSUFFICIENT_RESOURCES = 5
        FT_INVALID_PARAMETER = 6
        FT_INVALID_BAUD_RATE = 7
        FT_DEVICE_NOT_OPENED_FOR_ERASE = 8
        FT_DEVICE_NOT_OPENED_FOR_WRITE = 9
        FT_FAILED_TO_WRITE_DEVICE = 10
        FT_EEPROM_READ_FAILED = 11
        FT_EEPROM_WRITE_FAILED = 12
        FT_EEPROM_ERASE_FAILED = 13
        FT_EEPROM_NOT_PRESENT = 14
        FT_EEPROM_NOT_PROGRAMMED = 15
        FT_INVALID_ARGS = 16
        FT_OTHER_ERROR = 17
        FT_IO_TIMEOUT = 32
        FT_IO_FAILED = 33
    End Enum
    Friend Enum BK_return As Short
        BK_OK = 0
        BK_IO_ERROR_USB = 1
        BK_IO_ERROR_BIK = 2
        BK_DEVICE_NOT_FOUND = 3
        BK_FAILED_INIT = 4
        BK_FAILED_CMD = 5
        BK_ERROR_CATCH = 6
        BK_IO_CRC_FAILED = 7
        BK_FAILED_ERASE = 8
        BK_TH_CANCELLED = 9
        BK_FIRMWARE = 10
        BK_BIKISOFT_REQUIRES_UPDATE = 11
        BK_FIRMWARE_REQUIRES_UPDATE = 13
        BK_NOT_CONNECTED = 12
        BK_CONSULT_NOINIT = 14
        BK_CONSULT_FAILED = 15
        BK_IO_TIMEOUT = 16
        BK_IO_BAD_HEADERS = 17
        BK_ATMEL_REQUIRES_REFLASH_8MHZ = 18
        BK_ATMEL_REQUIRES_REFLASH_12MHZ = 19
        BK_ATMEL_REQUIRES_REFLASH_16MHZ = 20
        BK_ATMEL_NO_REFLASH = 21
    End Enum
    Friend Enum FT_Bits As Short
        FT_BITS_8 = 8
        FT_BITS_7 = 7
    End Enum
    Friend Enum FT_Stop_Bits As Short
        FT_STOP_BITS_1 = 0
        FT_STOP_BITS_1_5 = 1
        FT_STOP_BITS_2 = 2
    End Enum
    Friend Enum FT_Parity As Short
        FT_PARITY_NONE = 0
        FT_PARITY_ODD = 1
        FT_PARITY_EVEN = 2
        FT_PARITY_MARK = 3
        FT_PARITY_SPACE = 4
    End Enum
    Friend Enum FT_Flow As Short
        FT_FLOW_NONE = &H0S
        FT_FLOW_RTS_CTS = &H100S
        FT_FLOW_DTR_DSR = &H200S
        FT_FLOW_XON_XOFF = &H400S
    End Enum
    Friend Enum FT_Purg As Short
        FT_PURGE_RX = 1
        FT_PURGE_TX = 2
    End Enum
    Friend Enum FT_Events As Integer
        FT_EVENT_RXCHAR = 1
        FT_EVENT_MODEM_STATUS = 2
    End Enum
    Friend Enum FT_Open As UInteger
        FT_OPEN_BY_SERIAL_NUMBER = 1
        FT_OPEN_BY_DESCRIPTION = 2
        FT_OPEN_BY_LOCATION = 4
    End Enum
    ' Flags for FT_OpenEx
    Const FT_OPEN_BY_SERIAL_NUMBER As Short = 1
    Const FT_OPEN_BY_DESCRIPTION As Short = 2

    ' Flags for FT_ListDevices
    Friend Const FT_LIST_BY_NUMBER_ONLY As Integer = &H80000000
    Const FT_LIST_BY_INDEX As Integer = &H40000000
    Const FT_LIST_ALL As Integer = &H20000000

    Friend WithEvents m_UsbCommHandler As Comm.UsbCommunicationHandle = Nothing
    Friend lngHandle As Integer = 0

    Friend m_ConsultReceiveBytes As Integer = -1

    ''' <summary>
    ''' This function can be called whenever, it will only truley initialise when the USB connection is down
    ''' Otherwise rely on timeouts etc to work out if the board is powered on etc
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Friend Function BikiRom_Init(Optional ByVal WaitForBootup As Boolean = True) As BK_return

        Debug.Print("mod_BikiUSB: BikiRom_Init")
        If m_UsbCommHandler Is Nothing Then
            m_UsbCommHandler = New Comm.UsbCommunicationHandle(True)
        End If
        If WaitForBootup Then
            If m_UsbCommHandler.Initialise() Then
                Return BK_return.BK_OK
            Else
                Return BK_return.BK_FAILED_INIT
            End If
        Else
            Return BK_return.BK_OK
        End If
    End Function

    Friend Function BikiRom_connect(Optional ByVal Explicit As Boolean = False) As BK_return
        Debug.Indent()
        Debug.Print("mod_BikiUSB: BikiRom_connect")
        If m_UsbCommHandler Is Nothing Then
            m_UsbCommHandler = New Comm.UsbCommunicationHandle(False)
        End If
    End Function
    Friend Function usb_read(Optional ByVal RxBytes As Integer = 0) As Byte()
        Dim f_BytesInBuffer As Integer = 0
        FT_GetQueueStatus(m_UsbCommHandler.Handle, f_BytesInBuffer)
        If RxBytes = 0 And f_BytesInBuffer > 0 Then
            Dim retBytes(f_BytesInBuffer - 1) As Byte
            FT_Read_Bytes(m_UsbCommHandler.Handle, retBytes(0), f_BytesInBuffer, RxBytes)
            ReDim Preserve retBytes(RxBytes - 1)
            Return retBytes
        ElseIf RxBytes > 0 Then
            Dim retBytes(2056) As Byte
            FT_Read_Bytes(m_UsbCommHandler.Handle, retBytes(0), RxBytes, RxBytes)
            If RxBytes > 0 Then
                ReDim Preserve retBytes(RxBytes - 1)
                Console.WriteLine("USB Read {0:G} bytes: " & cv_HexFromBytes(retBytes), RxBytes)
                Return retBytes
            Else
                Return Nothing
            End If
        End If
        Return Nothing
    End Function

    ''' <summary>
    ''' Sends a new BikiSoft Frame, and attempts to receive a response frame if required.
    ''' </summary>
    ''' <param name="iData">Complete Frame</param>
    ''' <param name="oData">Response Frame</param>
    ''' <param name="ReadResponse">If a response is required</param>
    ''' <returns>Physical USB Layer return paramaters</returns>
    ''' <remarks>All Frame layer responses are in the oData and not handled in this layer</remarks>
    ''' 
    Friend Function BikiRom_read(ByVal ReturnLen As Integer) As Byte()
        Dim return_(ReturnLen - 1) As Byte
        Dim f_retCount As Integer = ReturnLen
        Dim flTimedout As Boolean = False
        Dim flFatalError As Boolean = False
        Dim lngTotalBytesRead As Integer = 0
        Dim ftStatus As Short
        Dim lngBytesRead As Integer = 0
        Dim byteArray(258) As Byte
        Dim arrayCursor As Short = 0
        Dim i As Short
        Dim f_count As Integer = 0
        If ReturnLen <> 0 Then
            flTimedout = False
            flFatalError = False

            '******************
            '** Wait for number of bytes code
            lngTotalBytesRead = 0
            Do
                lngBytesRead = 0
                ftStatus = FT_Read_Bytes(lngHandle, byteArray(0), f_retCount, lngBytesRead)
                'Debug.Print("FT_Read - send# :" & f_retCount & " Read: " & lngTotalBytesRead)
                If (ftStatus = FT_return.FT_OK) Or (ftStatus = FT_return.FT_IO_ERROR) Then
                    If lngBytesRead > 0 Then
                        For i = 1 To lngBytesRead
                            return_(arrayCursor) = byteArray(i - 1)
                            arrayCursor += 1
                        Next
                        lngTotalBytesRead += lngBytesRead
                        f_retCount -= lngBytesRead
                    Else

                        flTimedout = True
                    End If
                Else
                    flFatalError = True
                End If
            Loop Until (lngTotalBytesRead >= ReturnLen) Or (flTimedout = True) Or (flFatalError = True)
        Else
            FT_Purge(lngHandle, FT_Purg.FT_PURGE_RX)
        End If
        '*******************
        '** Return Code
        'Debug.Print("timeout: " & flTimedout & " Ioerror: " & flFatalError)
        Return return_
    End Function

    Private Function inv(ByRef byte_ As Byte) As Byte
        inv = 0
        Dim m_loop As Byte

        For m_loop = 0 To 7
            If BitIsSet_byte(byte_, m_loop) Then
                inv = BitSet_byte(inv, 7 - m_loop)
            End If
        Next
    End Function

    Friend Function Crc_byte(ByRef first_ As Byte, ByRef second_ As Byte) As Byte
        If first_ = second_ Then
            Crc_byte = 0
        Else
            Crc_byte = first_ Xor second_
        End If
    End Function
    Private Function byte_String(ByRef byte_ As Byte) As String
        If byte_ <= 15 Then
            byte_String = "0" & Mid(Hex(byte_), 2, 1)
        Else
            byte_String = Hex(byte_)
        End If
    End Function

    Friend Sub BikiRom_SetTimeoutHigh(ByVal bool As Boolean)
        If Not IsNothing(m_UsbCommHandler) Then
            If bool Then
                m_UsbCommHandler.Timeout = 10000
            Else
                m_UsbCommHandler.Timeout = 100
            End If
        End If
    End Sub
    Friend Sub BikiRom_SetTimeout(ByVal TimeOut As Integer)
        If Not IsNothing(m_UsbCommHandler) Then
            m_UsbCommHandler.Timeout = TimeOut
        End If
    End Sub

    ' This function Takes 0-4 and erases that sector or entire flash for mode 4
    Friend Function BikiRom_EraseSector(ByVal sector As BikiAction) As BK_return
        Dim f_Frame As Comm.Comm_Frame
        m_UsbCommHandler.Timeout = 12000
        Try
            Select Case sector
                Case BikiAction.BK_MAP1
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H0, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                Case BikiAction.BK_MAP2
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H10000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                Case BikiAction.BK_MAP3
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H20000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                Case BikiAction.BK_CFG
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H30000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H38000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H3A000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                    f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H3C000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASESECTOR)
                    m_UsbCommHandler.SendFrame(f_Frame)
                Case BikiAction.BK_ALL
                    If m_UsbCommHandler.BoardVersion = Comm.UsbBikiromInformation._BoardVersion.BikiRomUSBV3 Then
                        f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H0, Comm.Comm_Frame.BikiFrameAction.RUN_ERASEBANK1)
                        m_UsbCommHandler.SendFrame(f_Frame)
                        f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H0, Comm.Comm_Frame.BikiFrameAction.RUN_ERASEBANK2)
                        m_UsbCommHandler.SendFrame(f_Frame)
                    Else
                        f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, &H3C000, Comm.Comm_Frame.BikiFrameAction.RUN_ERASEALL)
                        m_UsbCommHandler.SendFrame(f_Frame)
                    End If

            End Select
        Catch exComm As Comm_Exceptions
            m_UsbCommHandler.Flush()
            Return BK_return.BK_IO_ERROR_BIK
        Catch exUsb As USB_exceptions
            m_UsbCommHandler.Flush()
            Return BK_return.BK_IO_ERROR_USB
        End Try
        m_UsbCommHandler.Timeout = 500
        Return BK_return.BK_OK
    End Function

    '    Friend Function BikiRom_EraseSector(ByVal sector As Integer) As Boolean
    '        Dim cmd() As Byte
    '        Dim s_init() As Byte = {0}
    '        Dim ret(10) As Byte

    '        If lngHandle <> 0 And sector >= 0 And sector <= 4 Then
    '            BikiRom_SetTimeoutHigh(True)
    '            Select Case sector
    '                Case BikiAction.BK_MAP1
    '                    cmd = cv_BytesFromHex("CC3400AF0000")
    '                    GoTo singleCmd
    '                Case BikiAction.BK_MAP2
    '                    cmd = cv_BytesFromHex("CC3400AF8000")
    '                    GoTo singleCmd
    '                Case BikiAction.BK_MAP3
    '                    cmd = cv_BytesFromHex("CC3401AF0000")
    '                    GoTo singleCmd
    '                Case BikiAction.BK_CFG
    '                    cmd = cv_BytesFromHex("CC3401AF8000")
    '                    If BikiRom_sendCmdd(cmd, ret, 6, 2) = True Then
    '                        If ret(1) = 170 Then
    '                            BikiRom_EraseSector = True
    '                        Else
    '                            BikiRom_EraseSector = False
    '                            Exit Function
    '                        End If
    '                    Else
    '                        BikiRom_EraseSector = False
    '                        Exit Function
    '                    End If
    '                    cmd = cv_BytesFromHex("CC3401AFC000")
    '                    If BikiRom_sendCmdd(cmd, ret, 6, 2) = True Then
    '                        If ret(1) = 170 Then
    '                            BikiRom_EraseSector = True
    '                        Else
    '                            BikiRom_EraseSector = False
    '                            Exit Function
    '                        End If
    '                    Else
    '                        BikiRom_EraseSector = False
    '                        Exit Function
    '                    End If
    '                    cmd = cv_BytesFromHex("CC3401AFD000")
    '                    BikiRom_sendCmdd(s_init, ret, 1, 0)
    '                    System.Threading.Thread.Sleep(20)

    '                    If BikiRom_sendCmdd(cmd, ret, 6, 2) = True Then
    '                        If ret(1) = 170 Then
    '                            BikiRom_EraseSector = True
    '                        Else
    '                            BikiRom_EraseSector = False
    '                            Exit Function
    '                        End If
    '                    Else
    '                        BikiRom_EraseSector = False
    '                        Exit Function
    '                    End If
    '                    cmd = cv_BytesFromHex("CC3401AFE000")
    '                    BikiRom_sendCmdd(s_init, ret, 1, 0)
    '                    System.Threading.Thread.Sleep(20)

    '                    If BikiRom_sendCmdd(cmd, ret, 6, 2) = True Then
    '                        If ret(1) = 170 Then
    '                            BikiRom_EraseSector = True
    '                        Else
    '                            BikiRom_EraseSector = False
    '                            Exit Function
    '                        End If
    '                    Else
    '                        BikiRom_EraseSector = False
    '                        Exit Function
    '                    End If
    '                Case BikiAction.BK_ALL
    '                    cmd = cv_BytesFromHex("CC3300")
    '                    If BikiRom_sendCmdd(cmd, ret, 3, 1) = True Then
    '                        If ret(0) = 170 Then
    '                            BikiRom_EraseSector = True
    '                        Else
    '                            BikiRom_EraseSector = False
    '                        End If
    '                    Else
    '                        BikiRom_EraseSector = False
    '                    End If
    '            End Select
    '        End If
    '        BikiRom_SetTimeoutHigh(False)
    '        Exit Function
    'singleCmd:
    '        If BikiRom_sendCmdd(cmd, ret, 6, 2) = True Then
    '            If ret(2) = 170 Then
    '                BikiRom_EraseSector = True
    '            Else
    '                BikiRom_EraseSector = False
    '            End If
    '        Else
    '            BikiRom_EraseSector = False
    '        End If
    '        BikiRom_SetTimeoutHigh(False)
    '    End Function

    ''' <summary>
    ''' Uploads an array given the mode change command in modeStr
    ''' </summary>
    ''' <param name="modeStr">Mode Change String</param>
    ''' <param name="data">Array to upload</param>
    ''' <param name="Packets">Number of 256byte packets to upload</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Friend Sub BikiRom_Reset()
        If Not IsNothing(m_UsbCommHandler) Then
            m_UsbCommHandler.ResetDevice()
        End If
    End Sub

    Friend Sub Close_Bikirom()
        If lngHandle <> 0 Then
            FT_Close(lngHandle)
            lngHandle = 0
        End If

    End Sub

End Module